const https = require("https");
const http = require("http");
const qs = require("querystring");
const _url = require("url")

module.exports = function(url, ops){
    // 根据地址中的协议判断，要使用http还是https发起请求
    const request = url.includes("https") ? https : http;
    // 因为request发送请求时，携带的cookie数据为数组形式，如：["name=val","age=val"]
    // 所以，将前端发送过来的cookie，解析成数组形式
    const cookie = qs.stringify(ops.cookie, ",").split(",");
    // 将目标地址解析成对象
    url = _url.parse(url);

    return new Promise((resolve)=>{
        // 准备发起请求
        const req = request.request({
            hostname: url.hostname,     // 请求目标地址
            path: url.pathname + "?" + qs.stringify(ops.data),  // 请求目标路径
            port: request === https ? 443 : 80,
            method: "GET",
            headers:{
                "Content-Type": "application/x-www-form-urlencoded",
                "Cookie": cookie
            }
        }, (res)=>{
            let str = "";
            res.on("data",(chunk)=>{
                str += chunk;
            })
            res.on("end",()=>{
                // 解析，并处理，目标接口返回的cookie信息
                const cookie = [];
                res.rawHeaders.forEach((val, idx, self)=>{
                    console.log(val);
                    if(val === "Set-Cookie"){
                        const oneCookie = self[idx+1].split("; ");
                        const obj = {};
                        oneCookie.forEach((val,idx)=>{
                            const item = val.split("=");
                            if(idx === 0){
                                obj.key = item[0];
                                obj.value = item[1];
                            }else{
                                obj[item[0]] = item[1];
                            }
                        })
                        obj.Expires = obj.Expires ? new Date(obj.Expires) : new Date();
                        cookie.push(obj)
                    }
                })
                // 将接收到的cookie信息和数据，返回给前端
                resolve({
                    data:str,
                    cookie:cookie
                });
            })
        })
        req.end();
    })
}
